import hashlib
import time
import urllib
import requests
import json
from bs4 import BeautifulSoup

with open("D:/appCache/新建文件夹 (2)/WXWork/1688850208204002/Cache/File/2021-03/localhost_access_log.2021-03-10.txt",
          "r") as f:
    for line in f.readlines():
        line = line.strip('/n')  # 去掉列表中每一个元素的换行符
        VERSION_TMP = line.split(' - - ')
        print(VERSION_TMP[0])
        SK = 'rprb8loXKqd6A9hRWDSCUHkvXz4DtSr8'
        AK = '7nsBOfpXLU6itL4nGWGo02IwErHXWhna'
        # 以get请求为例http://api.map.baidu.com/geocoder/v2/?address=百度大厦&output=json&ak=yourak
        queryStr = '/location/ip?ak='+AK+ '&ip='+VERSION_TMP[0]+'&coor=bd09ll'

        # 对queryStr进行转码，safe内的保留字符不转换
        encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")

        # 在最后直接追加上yoursk
        rawStr = encodedStr + SK
        raw = urllib.parse.quote_plus(rawStr)
        # print(hashlib.md5(raw.encode('utf8')).hexdigest())

        url='http://api.map.baidu.com'+queryStr+'&sn='+hashlib.md5(raw.encode('utf8')).hexdigest()
        resp = requests.get(url)

        # soup = BeautifulSoup(resp.text,'lxml')
        # print(resp.text)
        obj = json.loads(resp.text )
        print(obj)
        print(obj['content']['address'])

        with open("d:/ip.txt","a") as f:
            f.write('\n'+VERSION_TMP[0]+'--'+obj['content']['address'])
        # print(resp.content.decode(resp.encoding))
        time.sleep(3)
        # print(resp)
